import Cookie from 'js-cookie'

const respCommon = {
  onFulfilled(response, options) {
    return response.data
  },
  onRejected(error, options) {
    console.log(error)
    console.log(error.response)
    const { message, response } = error
    const { toast } = options
    let msg = ""
    switch (true) {
      case message.includes("Request failed with status code"):
        // 数据正常读取
        if (response && response.data) {
          if (response.data.msg) {
            msg = response.data.msg
          }
          // token 过期，重新登录
          if (response.data.code === 10105) location.href = '/login'
        }
        else msg = "系统接口 " + response.config.url.substring(4) + " 异常"
        break
      case message.includes("timeout"):
        message = "系统接口请求超时"
        break
      case "Network Error":
        message = "后端接口连接异常"
        break
    }
    if (msg) toast.fail(msg)
    return Promise.reject(message)
  }
}

const reqCommon = {
  /**
   * 发送请求之前做些什么
   * @param config axios config
   * @param options 应用配置 包含: {router, i18n, store, message}
   * @returns {*}
   */
  onFulfilled(config, options) {
    const { toast } = options
    const { url, xsrfCookieName } = config
    if (url.indexOf('login') === -1 && url.indexOf('register') === -1 && url.indexOf('code') === -1 && xsrfCookieName && !Cookie.get(xsrfCookieName)) {
      toast.fail('认证 token 已过期，请重新登录')
    }
    return config
  },
  /**
   * 请求出错时做点什么
   * @param error 错误对象
   * @param options 应用配置 包含: {router, i18n, store, message}
   * @returns {Promise<never>}
   */
  onRejected(error, options) {
    const {message} = options
    message.fail(error.message)
    return Promise.reject(error)
  }
}

export default {
  request: [reqCommon], // 请求拦截
  response: [respCommon] // 响应拦截
}
